package giro.general.rss;


import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.text.Html;
import android.util.Log;

public class RssReader {

	/**
	 * This method defines a feed URL and then calles our SAX Handler to read
	 * the article list from the stream
	 * 
	 * @return List<JSONObject> - suitable for the List View activity
	 */
	public static List<JSONObject> getLatestRssFeed(int mode) {
		String feed = "";
		if (mode == 0) {
			feed = "http://feeds.spaziociclismo.it/rss/";
		} else if (mode == 1){
			feed = "http://feeds.spaziociclismo.it/rss/?c=46";
		} else if (mode == 2){
			feed = "http://feeds.spaziociclismo.it/rss/?c=2";
		} else if (mode == 3){
			feed = "http://feeds.spaziociclismo.it/rss/?c=43";
		}else if (mode == 4){
			feed = "http://feeds.spaziociclismo.it/rss/?c=41";
		}else if (mode == 5){
			feed = "http://feeds.spaziociclismo.it/rss/?c=21";
		}
		RSSHandler rh = new RSSHandler();
		List<Article> articles = rh.getLatestArticles(feed);
		Log.e("RSS ERROR", "Number of articles " + articles.size());
		return fillData(articles);
	}

	/**
	 * This method takes a list of Article objects and converts them in to the
	 * correct JSON format so the info can be processed by our list view
	 * 
	 * @param articles
	 *            - list<Article>
	 * @return List<JSONObject> - suitable for the List View activity
	 */
	private static List<JSONObject> fillData(List<Article> articles) {

		List<JSONObject> items = new ArrayList<JSONObject>();
		for (Article article : articles) {
			JSONObject current = new JSONObject();
			try {
				buildJsonObject(article, current);
			} catch (JSONException e) {
				Log.e("RSS ERROR", "Error creating JSON Object from RSS feed");
			}
			items.add(current);
		}

		return items;
	}

	/**
	 * This method takes a single Article Object and converts it in to a single
	 * JSON object including some additional HTML formating so they can be
	 * displayed nicely
	 * 
	 * @param article
	 * @param current
	 * @throws JSONException
	 */
	private static void buildJsonObject(Article article, JSONObject current) throws JSONException {
		String title = article.getTitle();
		String description = article.getDescription();
		String date = article.getPubDate();
		URL url = article.getUrl();

		StringBuffer sbTitle = new StringBuffer();
		sbTitle.append(title);
		StringBuffer sbDescription = new StringBuffer();
		sbDescription.append(description);
		StringBuffer sbDate = new StringBuffer();
		sbDate.append(date);

		current.put("description", Html.fromHtml(sbDescription.toString()));
		current.put("title", Html.fromHtml(sbTitle.toString()));
		current.put("url", url.toString());
		current.put("date", Html.fromHtml(sbDate.toString()));
	}
}
